package com.ego.e.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.View

/**
 * @see Adapter
 * @see AdapterX
 * Created by lxy on 2017/5/21.
 */
abstract class EAdapter<Data>(var context: Context, var datas: MutableList<Data>) : RecyclerView.Adapter<EAdapter.EHolder>() {

    var listener: EListener<Data>? = null

    override fun getItemCount(): Int {
        return datas.size
    }

    fun get(): MutableList<Data>{
        return datas
    }

    fun set(datas: MutableList<Data>) {
        this.datas = datas
    }

    fun update(datas: MutableList<Data>) {

        this.datas.clear()
        this.datas.addAll(datas)
        notifyDataSetChanged()
    }

    fun item(position: Int): Data {
        return datas!!.get(position)
    }

    fun append(data: Data) {
        this.datas.add(data)
        notifyItemInserted(datas.size - 1)
    }

    fun append(list: MutableList<Data>) {
        this.datas.addAll(list)
        notifyDataSetChanged()
    }

    fun remove(position: Int) {
        datas.removeAt(position)
        notifyItemRemoved(position)
        if (position != datas.size) {
            notifyItemRangeChanged(position, datas.size - position)
        }
    }

    fun remove(data: Data) {
        var index = this.datas.indexOf(data)
        if (index != -1) {
            remove(index)
        }
    }

    fun isEmpty(): Boolean {
        return datas.isEmpty()
    }

    fun clear() {
        datas.clear()
    }

    protected fun onBindListener(view: View, data: Data, position: Int) {
        view.setOnClickListener {
            if (listener != null) {
                listener!!.onClick(view, data, position)
            }
        }
    }

    interface EListener<Data> {
        fun onClick(target: View, data: Data, position: Int)
    }

    class EHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        fun <V : View> find(id: Int): V {
            return EHolder.find(itemView, id)
        }

        /**同伴对象*/
        companion object {

            /**相当于java静态函数*/
            @JvmStatic fun <V : View> find(convertView: View, id: Int): V {
                var holder = convertView.tag
                if (holder == null) {
                    holder = SparseArray<V>()
                    convertView.tag = holder
                }

                var childView: V? = (holder as SparseArray<V>).get(id)
                if (childView == null) {
                    childView = convertView.findViewById(id) as V
                    holder.put(id, childView)
                }
                return childView
            }

        }
    }

}